module Gadgets
  class RadioGroup < Gtk::HBox
    def initialize(type = :horizontal)
      super()
      
      if type == :vertical
       @box = Gtk::VBox.new
      else
       @box = Gtk::HBox.new
      end
      self.pack_start(@box, false, false)
      
      @data = []
      @group = nil
    end
    
    def add_element(key, name = nil, component = nil, type = :label)
      name = key unless name
      
      t_name = name
      t_name = "" unless type == :label
      
      if @group
        b = Gtk::RadioButton.new(@group, t_name)
      else
        b = Gtk::RadioButton.new(t_name)
        @group = b
        b.active = true
      end
      @data << {:radio => b, :key => key, :name => name, :component => component}
      t = Gtk::HBox.new
      t << b
      t << component if component
      
      if type == :frame
        frame = Gtk::Frame.new(name)
        t = frame << t
      end
      @box.pack_start(t, false, false)
      @box.show_all
    end
    
    def selected_key
      selected_item = nil
      @data.each do |item|
        if item[:radio].active?
          return item[:key]
        end
      end
      return nil
    end
    
    def selected_key=(key)
      @data.each do |item|
        if item[:key] == key
          item[:radio].active = true
        end
      end
    end
    
    def selected_component
      selected_item = nil
      @data.each do |item|
        if item[:radio].active?
          return item[:component]
        end
      end
      return nil
    end
  end
end